﻿#region Copyright 
/*-------------------------------------------------------------------------
* 命名空间名称/文件名:    SSPivot.Admin.Core.DbContexts/SSPivotDbContextFactory 
* CLR版本:     4.0.30319.42000
* 机器名称:    DESKTOP-NHMLO8A
* 功 能：       N/A
* 类 名：       SSPivotDbContextFactory
* 创建时间：  2025/5/24 18:37:37
* 版本号：      v1.0
* 创建人:        xulong
*-------------------------------------------------------------------------*/
#endregion
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SSPivot.AspNetCore.Repository;
using SSPivot.Data.MultiTenancy;
using SSPivot.Common.Helpers;
using SSPivot.AspNetCore.Config;
using SSPivot.Common;

namespace SSPivot.Admin.Core.DbContexts
{ 
     public class SSPivotDbContextFactory : DbContextFactory,IDesignTimeDbContextFactory<SSPivotDbContext>
    {
      
        public override SSPivotDbContext CreateReadDbContext(string[] args)
        {
            var configuration = BuildConfiguration();
            var config = configuration.GetSection("DbConfig").Get<DbConfig>();// ConfigHelper.GetOptions<DbConfig>("DbConfig");
            var _loadBalancer = AppDependencyResolver.Current.GetService<IDbLoadBalancer>();
            var connectionString = _loadBalancer.GetReadConnection(config);
            var build = new DbContextOptionsBuilder<SSPivotDbContext>().UseLazyLoadingProxies();
            build.UseDatabase(config.DatabaseType, connectionString);
            return new SSPivotDbContext(build.Options);
        }
        public override SSPivotDbContext CreateDbContext(string[] args)
        {
            var configuration = BuildConfiguration();
            var config = configuration.GetSection("DbConfig").Get<DbConfig>();// ConfigHelper.GetOptions<DbConfig>("DbConfig");
            var connectionString = config.MasterDb;
            var build = new DbContextOptionsBuilder<SSPivotDbContext>().UseLazyLoadingProxies();
            build.UseDatabase(config.DatabaseType, connectionString);
            return new SSPivotDbContext(build.Options);
        }
        private static IConfigurationRoot BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Path.Combine(Directory.GetCurrentDirectory()))
                .AddJsonFile("appsettings.json", optional: false);
            return builder.Build();
        }
         
    }
}
